<template>
  <div v-show="!isMain && !isView" class="add-equip-detail">
    <px-scrollbar class="add-equip-content">
      <px-button style="margin: 16px 0 -4px" type="primary" icon="ArrowLeft" @click="backMainPage">返回</px-button>
      <px-form ref="formRef" :inline="true" :model="formValue" :rules="rules" label-position="right" label-width="150px">
        <EditDropDown dropdownTitle="基本信息">
          <template v-slot:content>
            <px-row>
              <px-col :span="8">
                <px-form-item label="盘点计划名称" prop="takePlanName">
                  <px-input v-model="formValue.takePlanName" placeholder="请输入盘点计划名称" maxlength="50" clearable />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="盘点计划编码" prop="takePlanCode">
                  <px-input v-model="formValue.takePlanCode" disabled placeholder="自动生成" maxlength="50" clearable />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <EquipClassSelect :isRequired="true" :className="formValue.className" @changeClassName="changeClassName" />
              </px-col>
              <px-col :span="8">
                <px-form-item label="盘点负责人" prop="takeStockPeople">
                  <px-select-v2
                    v-model="formValue.takeStockPeople"
                    filterable
                    clearable
                    :options="takeStockPeopleList"
                    placeholder="请选择盘点负责人"
                    @change="principalChange"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="16">
                <px-form-item label="备注" prop="remark">
                  <px-input
                    v-model="formValue.remark"
                    type="textarea"
                    placeholder="请输入备注"
                    :autosize="{ minRows: 1, maxRows: 4 }"
                    maxlength="1000"
                  />
                </px-form-item>
              </px-col>
            </px-row>
          </template>
        </EditDropDown>
        <EditDropDown dropdownTitle="执行周期">
          <template v-slot:content>
            <ExecutionCycle :form-value="formValue" @change="handelExecutionCycleChange" />
          </template>
        </EditDropDown>
        <EditDropDown dropdownTitle="工具盘点列表">
          <template v-slot:content>
            <px-row style="width: 100%">
              <px-col :span="8">
                <px-form-item label="盘点范围" prop="takeStockScope">
                  <px-select
                    v-model="formValue.takeStockScope"
                    placeholder="请先选择工具所属科室"
                    :disabled="!formValue.className"
                    filterable
                    clearable
                    style="width: 100%; margin-right: 16px"
                    @change="changeTakeStockScope"
                  >
                    <px-option v-for="item in takeStockScopeList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-button v-if="formValue.takeStockScope === 'choose'" type="primary" @click="dialogVisible = true">选择工具</px-button>
              </px-col>
            </px-row>
            <px-table :data="formValue.toolInfoDTOList" class="custom-table" :max-height="250" border>
              <px-table-column prop="toolCode" label="工具编码" min-width="140" show-overflow-tooltip />
              <px-table-column prop="toolName" label="工具名称" min-width="140" show-overflow-tooltip />
              <px-table-column prop="factoryAreaDesc" label="厂区" min-width="100" show-overflow-tooltip />
              <px-table-column prop="toolStatusDesc" label="工具状态" min-width="120" show-overflow-tooltip>
                <template #default="scope">
                  <px-tag
                    effect="plain"
                    :style="{
                      color: 'rgba(0, 0, 0, 0.8)',
                      border: `1px solid ${tagBorderColorList[scope.row.toolStatus]}`,
                      backgroundColor: `${tagBgColorList[scope.row.toolStatus]}`
                    }"
                  >
                    {{ scope.row.toolStatusDesc }}
                  </px-tag>
                </template>
              </px-table-column>
              <px-table-column prop="toolCategoryDesc" label="工具分类" min-width="100" show-overflow-tooltip />
              <px-table-column prop="toolUnitDesc" label="工具单位" min-width="100" show-overflow-tooltip />
              <px-table-column prop="toolModel" label="型号/规格" min-width="120" show-overflow-tooltip />
              <px-table-column prop="brandVal" label="品牌" min-width="120" show-overflow-tooltip />
              <px-table-column prop="toolPosition" label="工具位置" min-width="120" show-overflow-tooltip />
              <px-table-column fixed="right" label="操作" min-width="64" align="center">
                <template #default="scope">
                  <px-tooltip content="删除" placement="top">
                    <px-button link type="danger" icon="Delete" @click="handleDeleteTool(scope.$index)" />
                  </px-tooltip>
                </template>
              </px-table-column>
            </px-table>
          </template>
        </EditDropDown>
      </px-form>
    </px-scrollbar>
    <!-- 选择工具弹窗 -->
    <AddSparePartsDialog :className="formValue.className" :visible="dialogVisible" @closeDialog="closeDialog" @addTableRow="addTableRow" />
    <div class="info-form-btns">
      <px-button @click="backMainPage">取消</px-button>
      <px-button v-if="formValue.planStatus !== 2" type="primary" plain @click="handleSubmit(formRef, 'draft')">保存草稿</px-button>
      <px-button type="primary" @click="handleSubmit(formRef)">发布盘点计划</px-button>
    </div>
  </div>
</template>
<script setup lang="ts">
import { addToolInventoryDraft, addToolInventoryList, detailToolInventoryList, getPlanCode, queryToolList } from "@/api/equip/toolManage";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import EquipClassSelect from "@/views/all/equip/components/EquipClassSelect.vue";
import { PxMessage, PxMessageBox } from "px-ui";
import { computed, reactive, ref, toRefs, watch } from "vue";
import AddSparePartsDialog from "../../inventory/components/AddSparePartsDialog.vue";
import ExecutionCycle from "./ExecutionCycle.vue";

// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["backMainPage", "queryTable"]);
// 父级传过来的值
const props = defineProps(["isMain", "isView", "drawerType", "shareData", "planId"]);
// 显示隐藏
const isMain = computed(() => props.isMain);
const isView = computed(() => props.isView);

// 页面本身的值
const formRef = ref();

const tagBorderColorList = {
  0: "#4CCBA1",
  1: "#F37272",
  2: "#F7B648",
  3: "#7997A8"
};

const tagBgColorList = {
  0: "#E8F8F3",
  1: "#FEECEC",
  2: "#FEF5E6",
  3: "#F7F7F7"
};

const state = reactive<any>({
  formValue: {
    execType: "2",
    execDurationUnit: "DAY",
    taskCreateTime: 1,
    className: ""
  },
  dialogVisible: false,
  takeStockScopeList: [
    { name: "全面盘点", value: "all" },
    { name: "指定盘点", value: "choose" }
  ],
  takeStockPeopleList: [] // 责任人下拉框
});

const { formValue, dialogVisible, takeStockScopeList, takeStockPeopleList } = toRefs(state);

// 表单校验规则
const rules = computed(() => ({
  takePlanCode: [{ required: true, message: "盘点计划编号不能为空", trigger: "blur" }],
  takePlanName: [{ required: true, message: "盘点计划名称不能为空", trigger: "blur" }],
  execStartDate: [
    {
      required: true,
      message: "请选择开始日期",
      trigger: "change"
    }
  ],
  execEndDate: [
    {
      required: true,
      message: "请选择结束日期",
      trigger: "change"
    }
  ],
  execDuration: [
    {
      required: true,
      message: "请选择执行时长",
      trigger: "blur"
    }
  ],
  taskCreateTime: [
    {
      required: true,
      message: "请选择任务生成并提醒时间",
      trigger: "change"
    }
  ]
}));

const handelExecutionCycleChange = val => {
  console.log("改变", val);
  Object.assign(formValue.value, val);
};

const handleDeleteTool = index => {
  formValue.value.toolInfoDTOList.splice(index, 1);
};

// 获取后端自动生成的工单号
const getToolCode = async () => {
  const data = await getPlanCode();
  formValue.value.takePlanCode = data;
};

// 获取takeStockPeopleName
const principalChange = val => {
  const arr = takeStockPeopleList.value.filter(item => {
    return item.value === val;
  });
  if (arr && arr.length > 0) {
    formValue.value.takeStockPeopleName = arr[0].label;
  }
};

// 获取范围
const changeTakeStockScope = async () => {
  formValue.value.toolInfoDTOList = [];
  if (formValue.value.takeStockScope === "all") {
    formValue.value.toolInfoDTOList = await queryToolList({ toolClassName: formValue.value.className });
  }
};

// 监视isMain和isView值
watch(
  () => [props.isMain, props.isView, props.drawerType],
  async () => {
    if (!props.isMain && !props.isView) {
      formRef.value?.resetFields();
      takeStockPeopleList.value = await getEmployeeIdAndName();
      if (props.drawerType === "add") {
        await getToolCode();
      } else if (props.drawerType === "edit") {
        await getDetail();
      } else if (props.drawerType === "copy") {
        await getDetail();
        await getToolCode();
      }
    } else {
      formValue.value = {
        execType: "2",
        className: "",
        systemCode: "",
        eqpId: "",
        eqpName: "",
        contentList: []
      };
    }
  }
);

// 获取详情接口
const getDetail = async () => {
  formValue.value = await detailToolInventoryList(props.planId);
  if (props.drawerType === "copy") {
    formValue.value.planName = "";
    formValue.value.execStartDate = "";
    formValue.value.execEndDate = "";
    formValue.value.planStatus = 1;
    formValue.value.execType = "2";
    delete formValue.value.id;
  }
};
// 返回主页面
const backMainPage = () => {
  PxMessageBox.confirm(`确认退出工单吗？退出后内容将不会保存，请谨慎操作`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      formRef.value.resetFields();
      emits("backMainPage");
    })
    .catch(() => {});
};

// 提交
const handleSubmit = async (formEl: any, type?: any) => {
  if (!formEl) return;
  const params = formValue.value;
  const { toolInfoDTOList } = params;
  const idList = toolInfoDTOList?.map(item => item.id);
  // 保存草稿不需要对数据进行校验
  if (type === "draft") {
    if (props.drawerType === "add" || props.drawerType === "copy") {
      await addToolInventoryDraft({ ...params, toolIdList: idList, execType: "2" });
      PxMessage.success("保存草稿成功");
      formRef.value.resetFields();
      emits("backMainPage");
      emits("queryTable");
    } else if (props.drawerType === "edit") {
      await addToolInventoryDraft({ id: props.planId, ...params, toolIdList: idList, execType: "2" });
      PxMessage.success("编辑草稿成功");
      formRef.value.resetFields();
      emits("backMainPage");
      emits("queryTable");
    }
  } else {
    await formEl.validate(async valid => {
      if (valid) {
        if (props.drawerType === "add" || props.drawerType === "copy") {
          await addToolInventoryList({ ...params, toolIdList: idList, execType: "2" });
          PxMessage.success("创建成功");
          formRef.value.resetFields();
          emits("backMainPage");
          emits("queryTable");
        } else if (props.drawerType === "edit") {
          await addToolInventoryList({ id: props.planId, ...params, toolIdList: idList, execType: "2" });
          PxMessage.success("编辑成功");
          formRef.value.resetFields();
          emits("backMainPage");
          emits("queryTable");
        }
      }
    });
  }
};
// 关闭子级dialog弹窗
const closeDialog = () => {
  dialogVisible.value = false;
};
// 选择备件后添加表格数据
const addTableRow = val => {
  formValue.value.toolInfoDTOList = formValue.value.toolInfoDTOList?.concat(val)?.filter((obj, index, self) => {
    return self.map(x => x.id).indexOf(obj.id) === index;
  });
};

// 科室组件调用父组件
const changeClassName = (val, isOnlyClass) => {
  formValue.value.className = val;
  if (!isOnlyClass) {
    formValue.value.takeStockScope = "";
    formValue.value.toolInfoDTOList = [];
  }
};
</script>
<style lang="scss" scoped>
@import url("@/views/all/equip/scss/add-detail.scss");

.inspect-table-view {
  .px-form-item {
    margin-bottom: 0;
  }
}

.inspect-table-edit {
  .px-form-item {
    padding-top: 16px;
  }

  .px-table__cell {
    padding: 0;
  }

  .px-form-item__content {
    padding-top: 16px;
  }

  :deep(.px-table__header) {
    .must::before {
      margin-right: 4px;
      color: var(--px-color-danger);
      content: "*";
    }
  }
}
</style>
